# -*- coding: utf-8 -*-

import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urlencode, datetime
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanPanzhihuaPolicy(BaseTaxPolicySpider):
    name = 'sichuan_panzhihua_policy'

    province = '四川省'
    city = '攀枝花市'
    # county = '滑县'
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['攀枝花市人民政府', "", "http://www.panzhihua.gov.cn/zwgk/fggw/szcwjk/index.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_request, meta={'item': item}, dont_filter=True)

    def parse_request(self, response, **kwargs):
        meta = response.meta
        base_url = response.xpath(".").re_first(r'url:"(.*?search.*?)"')
        siteId = response.xpath(".").re_first(r'siteId:(\d+),')
        chanIds = response.xpath(".").re_first(r'chanIds:(\d+),')
        # meta['url'] = url

        params = {
            'pageSize': '20',
            'pageIndex': '1',  # 初始页码
            'siteId': siteId,
            'chanIds': chanIds,
            'title': '',
            'content': '',
            'zcPolicytype': '',
            'zcRefnoNumber': '',
            'zcRefnoText': '',
            'theme': '',
            'subject': '',
            'startTime': '2014-01-01',  # 起始时间
            'endTime': str(datetime.datetime.now() + datetime.timedelta(days=1)).split(' ')[0]     # 结束时间
        }
        meta['params'] = params

        yield scrapy.Request(
            url=f"{response.urljoin(base_url)}?{urlencode(params)}",
            callback=self.parse_list,
            meta=meta,
        )

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        params = meta.get('params')
        datas = response.json()
        elem_list = datas['documentVOs']
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['writeTime']
            item['title'] = elem['title']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(params, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if meta.get('is_next') is not False:
            pages = datas['pageCount']
            print(response.url, 'total', pages)
            meta.update({'item': prev_item, 'is_next': False})
            for page in range(2, pages + 1):
                params['pageIndex'] = str(page)
                yield response.follow(response.url.split('?')[0] + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("//div[@class='ele']/div[contains(text(), '发布日期')]/following-sibling::div/text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_panzhihua_policy".split())
